package com.oaec.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;

/**
 * Servlet Filter implementation class EncodeFilter
 */
@WebFilter(
		filterName="encodeFilter",//过滤器的别名
		urlPatterns = { "/*" }, //拦截的内容或者路径
		initParams = { //过滤器参数
				@WebInitParam(name = "encode", value = "UTF-8", description = "编码方式"),
				@WebInitParam(name = "forceEncoding", value = "true", description = "强制编码")
		})
public class EncodeFilter implements Filter {
	private String encode="ISO8859-1";//默认编码方式
    /**
     * Default constructor. 
     */
    public EncodeFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		request.setCharacterEncoding(encode);//让容器自动将客户端提交过来的数据转换成encode对应的编码方式
		response.setCharacterEncoding(encode);//让容器自动将响应给浏览器的内容或数据转换成encode对应的编码方式
		HttpServletRequest httpServletRequest=(HttpServletRequest)request;
		System.out.println(httpServletRequest.getRequestURL());
		System.out.println(httpServletRequest.getRequestURI());
		System.out.println(encode);
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		String code=fConfig.getInitParameter("encode");
		
		if(code!=null&&!"".equals(code)){
			this.encode=code;//存配置文件中的编码到属性
		}
	}

}
